<?php
  /**
  * for get ajax data for specify ctrl name
  * the template name format "ajax_$func_$ctrl.htm"
  */
  function VoteData_ajax_list() {
    //$ctrl the class name
    $ctrl    = FormUtil::getPassedValue ('ctrl', false , 'GET');

    //$method the method of request for edit or view enum[ view | form | delete | list | page]
    $func  = FormUtil::getPassedValue ('func', 'list' , 'GET');
    //pagnigation variable
    $filter  = FormUtil::getPassedValue ('filter', 0);
    $offset  = FormUtil::getPassedValue ('startnum', 0);
    $sort    = FormUtil::getPassedValue ('sort', '');


    $pagesize = FormUtil::getPassedValue ('pagesize', 100 , 'GET');
    $render = pnRender::getInstance('VoteData');
    $render->assign ('_GET', $_GET);
    $render->assign ('_POST', $_POST);
    $render->assign ('_REQUEST', $_REQUEST);

    if ($class = Loader::loadClassFromModule ('VoteData', 'Ajax' . ucfirst($ctrl), true)){

      $objectArray = new $class ();
      $where   = null;
      $sort = null;
      if (method_exists($objectArray,'genPermission')){
        $permit = $objectArray->genPermission();
        if (empty($permit)){
          return LogUtil::registerError ("ส่วนนี้ถูกจำกัดให้ใช้ได้เฉพาะสมาชิกเท่านั้น");
        }
      }
      if (method_exists($objectArray,'genFilter')){
        $where = $objectArray->genFilter();
      }

      if (method_exists($objectArray,'genSort')){
        $sort = $objectArray->genSort();
      }
      if (method_exists($objectArray,'selectExtendResult')){
        $resultex = $objectArray->selectExtendResult();
        $render->assign('extendResult', $resultex);
      }
      if (empty($where)){
        $where = $objectArray->_objWhere;
      }
      if (empty($sort)){
        $sort = $objectArray->_objSort;
      }
      $objectArray->get ($where, $sort , $offset, $pagesize);
      //var_dump($objectArray);
      //assign to view
      $render->assign('objectArray', $objectArray->_objData);
    }
    $render->assign('ctrl', $ctrl);

    if ($lang){
      $render->assign('lang', $lang);
    }else{
      $render->assign('lang', pnUserGetLang());
    }
    echo $render->fetch('ajax_'.$func.'_'.strtolower($ctrl).'.htm');
    return true;
  }

  function fixEncoding($in_str) { 
    $cur_encoding = mb_detect_encoding($in_str) ; 
    if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8")) 
      return $in_str; 
    else 
      return utf8_encode($in_str); 
  } 

  function VoteData_ajax_migrate(){
    $step =  FormUtil::getPassedValue ('step', null);
    $file =  FormUtil::getPassedValue ('file', null);
    $id =  FormUtil::getPassedValue ('id', null);
    switch ($step){
        case 1:
                //Read data from csv & Insert csv data to temp data
                $handle = fopen($file, "r");
                if($handle!==false){
                  $row = 0; 
                  $dataArray = array();
                  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if($row > 0){
                        $dataArray[] =$data;
                    }
                    $row++;
                  }
                  //Merge array
                  $size_i = sizeof($dataArray);
                  $report_id = 0;
                  for ($i = 0; $i < $size_i; $i++) {
                    $size_j = sizeof($dataArray[$i]);
                    for ($j = 0; $j < $size_j; $j++) {
                      if($j == 0){
                        $report_id = $dataArray[$i][0];
                      }else{
                          if($j%2 == 0){
                            $remark[] =$dataArray[$i][$j];
                          }else{
                            $reportID[] = $report_id;
                            $remarkID[] = $dataArray[$i][$j];
                          }
                      }
                    }
                  }
    /*
                  var_dump(sizeof($remarkID));
                  $size_remark = sizeof($remarkID);
                  for ($k = 0; $k < $size_remark; $k++) {
                    $tempArray[] = array(
                                         'id'        => (int)substr($remarkID[$k], 0, -1) ,
                                         'report_id' => $reportID[$k],
                                         'remark_id' => $remarkID[$k],
                                         'remark'    => $remark[$k]
                                      );
                  }
                  DBUtil::insertObjectArray($tempArray, 'votedata_person_temp', true);
    */

                  //Insert migrate status (1:insert csv to temp finish)
                  $size_remark = sizeof($remarkID);
                  $object = array(
                                   'all_csv' => $size_remark,
                                   'all_data' => $size_remark,
                                   'status'=> '1'
                                  );
                  $where  = "mig_id = $id ";
                  DBUtil::updateObject($object, 'votedata_migrate', $where);

                  //Regenerate array for insert to DB
                  $count = 1;
                  for ($k = 0; $k < $size_remark; $k++) {
                    $tempArray = array(
                                         'id'        => (int)substr($remarkID[$k], 0, -1) ,
                                         'report_id' => $reportID[$k],
                                         'remark_id' => $remarkID[$k],
                                         'remark'    => $remark[$k]
                                      );
                    DBUtil::insertObject($tempArray, 'votedata_person_temp', true);

                    $object = array('current_csv' => $count++);
                    $where  = "mig_id = $id ";
                    DBUtil::updateObject($object, 'votedata_migrate', $where);
                  }

                  unset($reportID);
                  unset($remarkID);
                  unset($remark);
                  unset($data);
                  unset($tempArray);
                  fclose($handle);
                  echo "finished";
                }
                break;
        case 2:
                //Data comparation
                $columnArray = array('id', 'remark');
                $tempArray = DBUtil::selectObjectArray( 'votedata_person_temp', '', '', -1, -1, '', null, null, $columnArray);

                $count = 1;
                foreach($tempArray as $key=>$value){
                    $object = array('per_remark' => $value[remark]);
                    $where  = "per_id = $value[id] ";
                    DBUtil::updateObject($object, 'votedata_person', $where);

                    $object = array('current_data' => $count++);
                    $where  = "mig_id = $id ";
                    DBUtil::updateObject($object, 'votedata_migrate', $where);
                }

                DBUtil::truncateTable('votedata_person_temp');
                break;
        case 3:
                //Complate task
                $fields = array('all_data', 'current_data');
                $result = DBUtil::selectObjectByID('votedata_migrate', $id, 'id', $fields);
                if($result[all_data] == $result[current_data]){
                  echo "task complete.";
                }else{
                  echo "task uncomplete.";
                }
                break;
    }
    pnShutDown();
  }

  function VoteData_ajax_csvprocess(){
    $id =  FormUtil::getPassedValue ('id', null);
    $fields = array('all_csv', 'current_csv');
    $result = DBUtil::selectObjectByID('votedata_migrate', $id, 'id', $fields);

    $csvprocess = ($result[current_csv] * 100)/$result[all_csv] ;
    $allcsv = $result[all_csv];
    $csv = $result[current_csv];
    header('Content-type: text/xml'); // define XML content type
    echo '<?xml version="1.0"?>';    // print XML header
    echo "<!--  -->";
    echo "<DOCUMENT><PROGRESS>".round($csvprocess,2)."</PROGRESS><ALLCSV>".$allcsv."</ALLCSV><CSV>".$csv."</CSV></DOCUMENT>";
    pnShutDown();
  }

  function VoteData_ajax_dataprocess(){
    $id =  FormUtil::getPassedValue ('id', null);
    $fields = array('all_data', 'current_data');
    $result = DBUtil::selectObjectByID('votedata_migrate', $id, 'id', $fields);
    $dataprocess = ($result[current_data] * 100)/$result[all_data] ;
    $alldata = $result[all_data];
    $data = $result[current_data];
    header('Content-type: text/xml'); // define XML content type
    echo '<?xml version="1.0"?>';    // print XML header
    echo "<!--  -->";
    echo "<DOCUMENT><PROGRESS>".round($dataprocess,2)."</PROGRESS><ALLDATA>".$alldata."</ALLDATA><DATA>".$data."</DATA></DOCUMENT>";
    pnShutDown();
  }